package cup.common.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @ProjectName: xbinfoportal
 * @Description: java类作用描述
 * @Author: xiaonan
 * @CreateDate: 2022/4/20 10:36
 * @UpdateUser: xiaonan
 * @UpdateDate: 2022/4/20 10:36
 * @UpdateRemark: The modified content
 * @Version: 1.0
 **/
public class DateUtil {

	protected static Logger logger = LoggerFactory.getLogger(DateUtil.class);
	//每秒25帧
	public static int fps = 25;
	//4k每秒50帧
	public static int fps4k = 50;

	/**
	 * java8 时间格式化为string
	 */
	public static String newDateFormatToStr(Date date,String pattern){
		LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
		return DateTimeFormatter.ofPattern(pattern).format(localDateTime);
	}

	/**
	 * java 时间格式化为Date
	 * yyyy-MM-dd
	 */
	public static Date newDateFormatToDate(String dataStr){
		LocalDate parse = LocalDate.parse(dataStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		return Date.from(parse.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
	}

	/**
	 * java时间格式化为Date
	 * yyyy-MM-dd
	 */
	public static Date newDateFormatToDateTime(String dateTimeStr){
		LocalDateTime parse = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		return Date.from(parse.atZone(ZoneId.systemDefault()).toInstant());
	}


	public static String dateToWeek(String datetime) {
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
		Calendar cal = Calendar.getInstance(); // 获得一个日历
		Date datet = null;
		try {
			datet = (Date) f.parse(datetime);
		} catch (ParseException e) {
		}
		cal.setTime(datet);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个周中的某天。
		if (w < 0)
			w = 0;
		return weekDays[w];
	}

	public static String addDay(String s, int n) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			Calendar cd = Calendar.getInstance();
			cd.setTime(sdf.parse(s));
			cd.add(Calendar.DATE, n);//增加一天
			//cd.add(Calendar.MONTH, n);//增加一个月

			return sdf.format(cd.getTime());

		} catch (Exception e) {
			return null;
		}
	}

	public static String getNextDay(Date date, int n) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DAY_OF_MONTH, +n);//+1今天的时间加一天
			date = calendar.getTime();
			return sdf.format(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getAddHoursDay(Date date, int n) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.HOUR_OF_DAY, +n);//+1今天的时间加一天
			date = calendar.getTime();
			return sdf.format(date);
		} catch (Exception e) {
			return null;
		}
	}


	public static String getNextDay(Date date, int n, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DAY_OF_MONTH, +n);//+1今天的时间加一天
			date = calendar.getTime();
			return sdf.format(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static Integer TimeCodeToframe(String timCode, Integer fpsInfo) {
		Integer frame = 0;
		if ("00:00:00:00".equals(timCode) || StringUtils.isEmpty(timCode)) {

			return frame;
		}
		String[] timeCodeArr = timCode.split(":");
		String h = timeCodeArr[0];
		String m = timeCodeArr[1];
		String s = timeCodeArr[2];
		String f = timeCodeArr[3];
		frame = (Integer.valueOf(h) * 3600 * fpsInfo) + (Integer.valueOf(m) * 60 * fpsInfo) + (Integer.valueOf(s) * fpsInfo) + Integer.valueOf(f);
		return frame;
	}


	//帧转变为日期
	public static String frameToTimeCode(Integer frames, Integer fpsInfo) {
		if (frames == null || frames == 0) {
			return "00:00:00:00";
		}
		Integer hour = 0;
		Integer minute = 0;
		Integer second = 0;
		Integer frame = 0;
		String timecode = "";

		hour = (int) Math.floor(frames / (60 * 60 * fpsInfo));
		frames = frames - hour * 60 * 60 * fpsInfo;

		minute = (int) Math.floor(frames / (60 * fpsInfo));
		frames = frames - minute * 60 * fpsInfo;

		second = (int) Math.floor(frames / fpsInfo);
		frames = frames - second * fpsInfo;

		frame = frames;

		if (hour < 10) timecode = timecode + "0";
		timecode = timecode + hour + ":";
		if (minute < 10) timecode = timecode + "0";
		timecode = timecode + minute + ":";
		if (second < 10) timecode = timecode + "0";
		timecode = timecode + second + ":";
		if (frame < 10) timecode = timecode + "0";
		timecode = timecode + frame;
		return timecode;
	}

	//帧转变为日期
	public static Long timeCodeStringToFrames(String timeCode, Integer fpsInfo) {
		if (timeCode == null)
			return null;
		if (timeCode.length() != 11)
			return 0L;

		String strHour = timeCode.substring(0, 2);
		String strMinute = timeCode.substring(3, 5);
		String strSecond = timeCode.substring(6, 8);
		String strFrame = timeCode.substring(9, 11);
		int nhour = Integer.valueOf(strHour).intValue();
		int nminute = Integer.valueOf(strMinute).intValue();
		int nsec = Integer.valueOf(strSecond).intValue();
		int nframe = Integer.valueOf(strFrame).intValue();

		return (long) (nhour * 3600 * fpsInfo + nminute * 60 * fpsInfo + nsec * fpsInfo + nframe);
	}

	/**
	 * 将字符串格式yyyyMMdd的字符串转为日期，格式"yyyy-MM-dd"
	 *
	 * @param date 日期字符串
	 * @return 返回格式化的日期
	 * @throws ParseException 分析时意外地出现了错误异常
	 */
	public static String strToDateFormat(String date) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		formatter.setLenient(false);
		Date newDate = formatter.parse(date);
		formatter = new SimpleDateFormat("yyyy-MM-dd");
		return formatter.format(newDate);
	}


	/**
	 * 将字符串格式yyyyMMdd的字符串转为日期，格式"yyyy-MM-dd"
	 *
	 * @param date 日期字符串
	 * @return 返回格式化的日期
	 * @throws ParseException 分析时意外地出现了错误异常
	 */
	public static String strToDateFormat1(String date) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		formatter.setLenient(false);
		Date newDate = formatter.parse(date);
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(newDate);
	}

	/**
	 * @param date
	 * @param day  想要获取的日期与传入日期的差值 比如想要获取传入日期前四天的日期 day=-4即可
	 * @return
	 */
	public static Date getSomeDay(Date date, int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, day);
		return calendar.getTime();
	}

	public static SimpleDateFormat getFormat(String format) {
		return new SimpleDateFormat(format);
	}

	/**
	 * 获取上周周几的日期,默认一周从周一开始
	 *
	 * @param dayOfWeek
	 * @param weekOffset
	 * @return
	 */
	public static Date getDayOfWeek(int dayOfWeek, int weekOffset) {
		return getDayOfWeek(Calendar.MONDAY, dayOfWeek, weekOffset);
	}

	/**
	 * 获取上(下)周周几的日期
	 *
	 * @param firstDayOfWeek {@link Calendar} 值范围 <code>SUNDAY</code>,
	 *                       <code>MONDAY</code>, <code>TUESDAY</code>,
	 *                       <code>WEDNESDAY</code>, <code>THURSDAY</code>,
	 *                       <code>FRIDAY</code>, and <code>SATURDAY</code>
	 * @param dayOfWeek      {@link Calendar}
	 * @param weekOffset     周偏移，上周为-1，本周为0，下周为1，以此类推
	 * @return
	 */
	public static Date getDayOfWeek(int firstDayOfWeek, int dayOfWeek, int weekOffset) {
		if (dayOfWeek > Calendar.SATURDAY || dayOfWeek < Calendar.SUNDAY) {
			return null;
		}
		if (firstDayOfWeek > Calendar.SATURDAY || firstDayOfWeek < Calendar.SUNDAY) {
			return null;
		}
		Calendar date = Calendar.getInstance(Locale.CHINA);
		date.setFirstDayOfWeek(firstDayOfWeek);
		// 周数减一，即上周
		date.add(Calendar.WEEK_OF_MONTH, weekOffset);
		// 日子设为周几
		date.set(Calendar.DAY_OF_WEEK, dayOfWeek);
		// 时分秒全部置0
		date.set(Calendar.HOUR_OF_DAY, 0);
		date.set(Calendar.MINUTE, 0);
		date.set(Calendar.SECOND, 0);
		date.set(Calendar.MILLISECOND, 0);
		return date.getTime();
	}

	public static String secToTime(int time) {
		String timeStr = null;
		int hour = 0;
		int minute = 0;
		int second = 0;
		if (time <= 0)
			return "00:00:00";
		else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = unitFormat(minute) + ":" + unitFormat(second);
			} else {
				hour = minute / 60;
				if (hour > 99)
					return "99:59:59";
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
			}
		}
		return timeStr;
	}

	public static String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10)
			retStr = "0" + Integer.toString(i);
		else
			retStr = "" + i;
		return retStr;
	}


	//返回的是字符串型的时间，输入的
	//是String day, int x
	public static String addDateMinut(String day, int x, String formatStr) {

		SimpleDateFormat format = new SimpleDateFormat(formatStr);// 24小时制
		//引号里面个格式也可以是 HH:mm:ss或者HH:mm等等，很随意的，不过在主函数调用时，要和输入的变
		//量day格式一致
		Date date = null;
		try {
			date = format.parse(day);
		} catch (Exception ex) {
		}
		if (date == null)
			return "";
		logger.info("获得的开始时间:" + format.format(date)); //显示输入的日期
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, x);// 24小时制
		date = cal.getTime();
		logger.info("获得的结束时间:" + format.format(date));  //显示更新后的日期
		cal = null;
		return format.format(date);

	}

	public static String timeStampToString(Timestamp timestamp, String pattern) {
		DateFormat sdf = new SimpleDateFormat(pattern);
		//方法一:优势在于可以灵活的设置字符串的形式。
		String tsStr = sdf.format(timestamp);
		return tsStr;
	}

	public static String gethhmmss(long time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date(time));
			calendar.add(Calendar.HOUR_OF_DAY, 0);//+1今天的时间加一天
			Date date = calendar.getTime();
			return sdf.format(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static String ymdhms(long time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date(time));
			calendar.add(Calendar.HOUR_OF_DAY, 0);//+1今天的时间加一天
			Date date = calendar.getTime();
			return sdf.format(date);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 比较两个时间的大小默认只取 年月日
	 *
	 * @param date1 yyyy-MM-dd
	 * @param date2 yyyy-MM-dd
	 * @return 1 / -1
	 */
	public static int dateCompate(Date date1, Date date2) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String strDate1 = sdf.format(date1);
		String strDate2 = sdf.format(date2);
		int varDate1 = Integer.parseInt(strDate1);
		int varDate2 = Integer.parseInt(strDate2);
		return Integer.compare(varDate1,varDate2);
	}
}
